var today = new Date();
var todayTxt = today.format('yyyy-MM-dd');

var AUTONOMY_EXAMINATION_DAILY = (function () {
    var dailyTable;

    /**
     * 数据查询接口的参数拼接
     */
    function getSearchParams() {
        var data = {};
        var $dtFrom = $('#dtFrom');
        if (!$dtFrom.val().length) {
            WeKnow.errorMsg('请输入查询开始日期');
            $dtFrom.focus();
            return false;
        }

        var dtFrom = $dtFrom.val();
        if (!MY_VALIDATOR.isDate(dtFrom, 'yyyy-MM-dd')) {
            WeKnow.errorMsg('查询开始日期格式不正确');
            $dtFrom.focus();
            return false;
        }
        data.dtFrom = dtFrom;

        // 查询日期to
        var $dtTo = $('#dtTo');
        if (!$dtTo.val().length) {
            WeKnow.errorMsg('请输入查询结束日期');
            $dtTo.focus();
            return false;
        }

        var dtTo = $dtTo.val();
        if (!MY_VALIDATOR.isDate(dtTo, 'yyyy-MM-dd')) {
            WeKnow.errorMsg('查询结束日期格式不正确');
            $dtTo.focus();
            return false;
        }
        if ($dtFrom.val() > $dtTo.val()) {
            WeKnow.errorMsg('开始时间不能大于结束时间');
            return false;
        }
        data.dtTo = dtTo;

        // 诊所名
        var searchName = $.trim($('#searchName').val());
        if (searchName.length) {
            data.name = searchName;
        }


        //异常类别
        var status = $("#enforcementStatus option:selected").val();
        data.enforcementSt = status;

        data.type = 0; //类别 0：全面自查   1：日常自查

        return data;
    }

    /**
     * 初始化表格
     */
    function initTable() {
        // console.log("加载表格");
        layui.use('table', function () {
            var table = layui.table;
            //执行一个laypage实例
            dailyTable = table.render({
                elem: '#demo',
                autoSort: false,
                height: $(document).height() - $('#demo').offset().top - 22,
                url: "invs_autonomy_examination.do/load",
                method: "POST",
                where: getSearchParams(),
                cellMinWidth: 80,
                page: true,
                limit: 10,
                limits: [10, 20, 50, 100],
                cols: [[
                    { field: 'institutionName', title: '机构名称', align: 'center', width: '20%' },
                    {
                        field: 'enforcementSt', title: '执法状态', align: 'center', width: '10%', templet: function (d) {
                            if (d.enforcementSt == '1') {
                                return "已执法";
                            } else {
                                return "未执法";
                            }
                        }
                    },
                    {
                        field: 'enforcementUser', title: '执法人员', align: 'center', width: '10%', templet: function (d) {
                            return d.enforcementUser ? d.enforcementUser : '/';
                        }
                    },

                    {
                        field: 'enforcementTm', title: '执法时间', align: 'center', width: '10%', templet: function (d) {
                            return d.enforcementTm ? new Date(d.enforcementTm).format('yyyy-MM-dd') : '/';
                        }
                    },


                    {
                        field: 'appealSt', title: '执法倒计时', align: 'center', width: '10%', templet: function (d) {
                            //已执法 或者 未执法并且已自查
                            if (d.enforcementSt == '1' || (d.enforcementSt != '1' && d.examinationSt == '1')) {
                                return "/";
                            } else {
                                return countdown(d.year, d.quarter);
                            }
                        }
                    },
                    {
                        field: 'enforcementResults', title: '执法结果', align: 'center', width: '30%', templet: function (d) {
                            return d.enforcementResults ? d.enforcementResults : '/';
                        }
                    },
                    {field:'operator', title:'操作', align:'center', width:'10%', toolbar: '#barDemo'},
                ]],
                done: function (res, curr, count) {
                    $(".layui-table-main  tr").each(function (index, val) {
                        $($(".layui-table-fixed .layui-table-body tbody tr")[index]).height($(val).height());
                    });
                }
            });


            //监听行工具事件
            table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data //获得当前行数据
                    ,layEvent = obj.event; //获得 lay-event 对应的值
                if(layEvent === 'operation'){
                    window.open('http://scq.139379.com:1168/new/');
                }
            });
        });
    }

    /**
     * 搜索
     */
    function search() {
        console.log("搜索");
        reloadTable();
    }

    /**
     * 表格重新加载
     */
    function reloadTable() {
        var params = {
            where: getSearchParams(),
            page: { curr: 1 },
        }
        dailyTable.reload(params);
    }

    /**
     * 倒计时算法
     */
    function countdown(year, quarter) {
        if (year ) {
            // var createDate = new Date(parseInt(date)); //此条记录创建时间
            // var createMonth = createDate.getMonth();
            // var createQuarter = Math.floor((createMonth % 3 == 0 ? (createMonth / 3) : (createMonth / 3 + 1)));//季度

            var currDate = new Date(); //当期时间
            var currMonth = currDate.getMonth(); //获取当前月份(0-11,0代表1月)
            var currQuarter = Math.floor((currMonth % 3 == 0 ? (currMonth / 3) : (currMonth / 3 + 1)));//当前季度

            if ((year + 1) == currDate.getFullYear()) {
                if (currMonth == 0) { //1月
                    var day = (7 - currDate.getDate()) < 0 ? 0 : (7 - currDate.getDate());
                    return day + "天";
                } else {
                    return "0天"
                }
            } else {
                return "0天";
            }
        } else {
            return "/";
        }

    }

    return {
        initTable: initTable,
        search: search
    }
})();

$(document).ready(function () {

    //初始化日期选择控件
    $(".my_date_control").datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: 'yy-mm-dd',//日期格式
        yearSuffix: '年', //年的后缀
        showMonthAfterYear: true,//是否把月放在年的后面
        maxDate: (function () {
            return todayTxt;
        })(),//最大日期
        yearRange: (function () {
            // '1990:2010'
            var year1 = '1900';
            var year2 = today.getFullYear();
            return year1 + ':' + year2;
        })(),
        monthNamesShort: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
        dayNamesMin: ['日', '一', '二', '三', '四', '五', '六'],
        onUpdatedDatepicker: function (_year, _month, _calendar) {
            // console.log('onUpdatedDatepicker');
            var $c = $('div#ui-datepicker-div');
            $c.find('td[data-handler="selectDay"]').each(function (idx, d) {
                var $d = $(d);
                $d.css({ 'pointer-events': 'auto', 'opacity': 1 });
            });
        }
    });

    /*var enforcementStatusChoose = $("#enforcementStatusChoose").val();
    $("#enforcementStatus").val(enforcementStatusChoose);*/

    //添加操作按钮
    var demo = document.getElementById("demo");
    demo.innerHTML += '<script type="text/html" id="barDemo">' +
        '{{# if(d.enforcementSt == 0){}}' +
        ' <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="operation">执法</' + 'a>' +
        '{{# } }}' +
        '</' + 'script>';

    //搜索按钮点击事件
    $('#search').click(function () {
        AUTONOMY_EXAMINATION_DAILY.search();
    })

    $('#import').click(function () {
        toWorkbench("invs_system_config.do","","","");
    })


    AUTONOMY_EXAMINATION_DAILY.initTable();
    // console.log("init");
});


//跳转工作台
function toWorkbench(title, status, date, otherData) {
	var today = $('.date_fillter').eq(0).val();// 0：今日  1：本周  2：近两个月  10：全部
	if(date == "all"){
		today = "10";
	} else {
		today = date;
	}
	// WeKnow.submit("main.do?initPageTitle="+ title +"&today=" + today + "&status=" + status + "&otherData=" + otherData);
	window.open("main.do?initPageTitle="+ title +"&today=" + today + "&status=" + status + "&otherData=" + otherData);
}
